package com.example.shop_2212.login

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.example.base.mvvm.BaseActivity
import com.example.base.net.Const
import com.example.shop_2212.R
import com.example.shop_2212.databinding.ActivityLoginBinding
import com.example.shop_2212.room.AppDBUtils

@Route(path = "/app/LoginActivity")
class LoginActivity : BaseActivity<ActivityLoginBinding,LoginViewModel>() {
    override fun initView() {
        binding.btnLogin.setOnClickListener {
            viewModel.login(binding.etUsername.text.toString(),binding.etPassword.text.toString(),0)
        }
        //来回切换登录方式
        binding.btnGologincode.setOnClickListener {
            finish()
            ARouter.getInstance().build("/app/LoginCodeActivity").navigation()
        }
    }

    override fun initData() {
        viewModel.loginSuccess.observe(this){
            if(it.code==Const.RESULT_OK){
                SPUtils.getInstance().put(Const.SP_TOKEN,it.data.token)
                SPUtils.getInstance().put("phone",it.data.phone)
                SPUtils.getInstance().put("uid",it.data.uid)//做了根据uid查询用户的功能，所以需要保存uid
                //保存用户信息到数据库
                AppDBUtils.getDB().getUserDao().insert(it.data)
                //查询数据库中的User
                val query = AppDBUtils.getUDao().query(SPUtils.getInstance().getInt("uid"))
                if(query!=null){
                    Log.d("sss", "initData: ${query.get(0)}")
                }

                ARouter.getInstance().build("/app/ShopActivity").navigation()
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.loginFail.observe(this){
            ToastUtils.showLong(it)
        }
    }

    override fun getViewModel(): Class<LoginViewModel>  = LoginViewModel::class.java

    override fun getLayout(): Int  = R.layout.activity_login

}